package cn.uc.ucgc.community.upgrade;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public abstract class Task implements Runnable {
    private static final Logger logger = LoggerFactory.getLogger(Task.class);
    /*任务描述信息 */
    private String taskDesc;
    /*任务是否正常完成*/
    private boolean finish;
    /*任务执行结果描述信息*/
    private String taskResult;

    public String getTaskDesc() {
        return taskDesc;
    }

    public abstract void doTask(StringBuilder sb) throws Exception;

    @Override
    public void run() {
        //开始时打印info级别日志
        String taskDesc = getTaskDesc();
        Utils.recordTaskBegin(logger, taskDesc);
        StringBuilder sb = new StringBuilder();
        sb.append(Constants.TASK_RESULT_PREFIX).append(taskDesc);
        try {
            //扩展实现
            doTask(sb);
            sb.append(Constants.TASK_RESULT_OK_SUFFIX);
            setFinish(true);
        } catch (Exception e) {
            logger.error("", e);
            setFinish(false);
            sb.append(Constants.TASK_RESULT_FAILED_SUFFIX);
        } finally {
            String rst = sb.toString();
            //汇总显示，可能会用到
            setTaskResult(rst);
            logger.warn(rst);//操作结果一定要显示
            Utils.recordTaskEnd(logger);
        }
    }

    protected void setTaskDesc(String taskDesc) {
        this.taskDesc = taskDesc;
    }

    public String getTaskResult() {
        return taskResult;
    }

    private void setTaskResult(String taskResult) {
        this.taskResult = taskResult;
    }

    public boolean isFinish() {
        return finish;
    }

    private void setFinish(boolean finish) {
        this.finish = finish;
    }
}
